package com.are.manejadores;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import com.are.entidades.Avance;
import com.are.odisea.db;

public class ManejadorAvances {
	private db conexion = null;
	private Avance avance;
	
	public db getConexion() {
		return conexion;
	}
	public void setConexion(db conexion) {
		this.conexion = conexion;
	}
	public com.are.entidades.Avance getAvance() {
		return avance;
	}
	public void setAvance(com.are.entidades.Avance avance) {
		this.avance = avance;
	}
	public ManejadorAvances(db conexion, Avance avance) {
		super();
		this.conexion = conexion;
		this.avance = avance;
	}
	public ManejadorAvances(db conexion) {
		super();
		this.conexion = conexion;
	}
	
	public boolean Add(String orden, String usuario, String avance) throws SQLException {
		boolean result = false;
		String sql = "INSERT INTO avances (orden,usuario,avance,fecha) values (?,?,?,SYSDATE())";
		java.sql.PreparedStatement pst = conexion.getConnection().prepareStatement(sql);
		pst.setString(1, orden);
		pst.setString(2, usuario);
		pst.setString(3, avance);
		if (conexion.Update(pst) > 0) {
			conexion.Commit();
			result = true;
		}
		return result;
	}
	
	public boolean Add(Avance avance) throws SQLException {
		boolean result = false;
		String sql = "INSERT INTO avances (orden,usuario,avance,fecha) values (?,?,?,SYSDATE())";
		java.sql.PreparedStatement pst = conexion.getConnection().prepareStatement(sql);
		pst.setString(1, avance.getOrden());
		pst.setString(2, avance.getUsuario());
		pst.setString(3, avance.getAvance());
		if (conexion.Update(pst) > 0) {
			conexion.Commit();
			result = true;
		}
		return result;
	}
	
	public ArrayList<Avance> List(String orden) throws SQLException {
		ArrayList<Avance> lista = new ArrayList<Avance>();
		String sql = "SELECT * FROM AVANCES WHERE ORDEN=?";
		java.sql.PreparedStatement pst = conexion.getConnection().prepareStatement(sql);
		pst.setString(1, orden);
		ResultSet rs = conexion.Query(pst);
		while (rs.next()) {
			Avance avance = new Avance();
			avance.setAvance(rs.getString("avance"));
			avance.setFecha(rs.getString("fecha"));
			avance.setOrden(rs.getString("orden"));
			avance.setId(rs.getString("id"));
			avance.setUsuario(rs.getString("usuario"));
			lista.add(avance);
		}
		
		return lista;
	}
	
	public int Count(String orden) throws SQLException {
		int contador =0;
		String sql = "SELECT orden,count(*) total FROM AVANCES WHERE ORDEN=? GROUP BY ORDEN";
		java.sql.PreparedStatement pst = conexion.getConnection().prepareStatement(sql);
		pst.setString(1, orden);
		ResultSet rs = conexion.Query(pst);
		if (rs.next()) {
			contador = rs.getInt("total");
		}
		return contador;
	}
	
}
